﻿using Css_VoteSys.Models.Database;
using Css_VoteSys.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Css_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CompanyController : ControllerBase
    {
        private readonly Css_VoteSysContext _db;
        private readonly IUserService _UserService;

        public CompanyController(Css_VoteSysContext db, IProjectService ProjectService, IUserService UserService)
        {
            _db = db;
            _UserService = UserService;
        }

        /// <summary>
        /// 创建公司信息(需登录)
        /// </summary>
        /// <param name="CompanyLogo">公司LOGO地址</param>
        /// <param name="CompanyName">公司名称</param>
        /// <param name="CompanyDescription">公司描述</param>
        /// <returns></returns>
        [HttpPost]
        public string CreateCompanyInfo(string CompanyLogo, string CompanyName, string CompanyDescription)
        {
            // 查询该用户是否创建过该项目 UserId CategoryId
            var UserId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
            if (UserId == null) { return "请先登录"; }
            if (_db.Companies.FirstOrDefault(x => x.UserId == Convert.ToInt32(UserId)) == null) {
                // 创建项目
                _db.Companies.Add(new Company
                {
                    UserId = Convert.ToInt32(UserId),
                    CompanyLogo = CompanyLogo,
                    CompanyName = CompanyName,
                    CompanyDescription = CompanyDescription
                });
                //保存更改
                var row = _db.SaveChanges();
                if (row > 0)
                    return "创建公司信息成功";
                return "创建公司信息失败";
            }
            return "该用户已提交过公司信息";
        }

        /// <summary>
        /// 查询所有公司信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<Company> SelectAllCompany() {
            return _db.Companies.ToList();
        }
    }
}
